package server.controller;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import plug.result.RetResponse;
import plug.result.RetResult;
import server.dao.AccountDao;
import server.dao.MoneyRecordDao;
import server.dao.TenantDao;
import server.model.entity.Account;
import server.model.entity.MoneyRecord;
import server.model.entity.Tenant;
import server.model.entity.Users;
import server.model.vo.IndexTitleUserVo;
import server.model.vo.IndexTitleVo;

import java.math.BigDecimal;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: 许哲
 * @createTime: 2021/11/25 20:53
 * @version: 1.0
 */
@RestController
@RequestMapping("v1/api/home")
public class IndexController {
    @Autowired
    private TenantDao tenantDao;
    @Autowired
    private AccountDao accountDao;
    @Autowired
    private MoneyRecordDao moneyRecordDao;

    @GetMapping("/title")
    public RetResult getTime() {
        Users users = (Users) SecurityUtils.getSubject().getSession().getAttribute("Users");
        if (users.getType().equalsIgnoreCase("ADMIN")) {
            IndexTitleVo indexTitleVo = new IndexTitleVo();
            indexTitleVo.setTenantCount(tenantDao.findAll().size());
            indexTitleVo.setAccountCount(accountDao.findAll().size());
            indexTitleVo.setMoneyDay(moneyRecordDao.findDay().stream().map(MoneyRecord::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add));
            indexTitleVo.setMoneyAll(moneyRecordDao.findAll().stream().map(MoneyRecord::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add));
            return RetResponse.makeOKRsp(indexTitleVo);
        } else {
            Tenant ten = tenantDao.findByUserId(users.getId());
            IndexTitleVo indexTitleVo = new IndexTitleVo();
            indexTitleVo.setTenantCount(moneyRecordDao.findDaySystem(ten.getCode()).size());
            indexTitleVo.setAccountCount(moneyRecordDao.findDaySystem(ten.getCode())
                    .stream()
                    .filter(item->item.getStatus().equals(MoneyRecord.STATUS.SUCCESS.getDisplay()))
                    .collect(Collectors.toList()).size()
            );
            indexTitleVo.setMoneyDay(moneyRecordDao.findDaySystem(ten.getCode()).stream().map(MoneyRecord::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add));
            indexTitleVo.setMoneyAll(moneyRecordDao.findSystem(ten.getCode()).stream().map(MoneyRecord::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add));
            return RetResponse.makeOKRsp(indexTitleVo);
        }
    }
}
